//
//  SearchDetailViewController.m
//  liwushuo
//
//  Created by qf1 on 16/4/19.
//  Copyright (c) 2016年 ZJH. All rights reserved.
//

#import "SearchDetailViewController.h"
#import "NetWorkManager.h"
#import "GuideContentTableViewCell.h"
#import "HotDetailViewController.h"
#import "DetailViewController.h"
#import "StyleLabel.h"

@interface SearchDetailViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (retain ,nonatomic)UIScrollView * mainScroll;
@property (retain ,nonatomic)NSMutableArray * presentArray;
@property (retain ,nonatomic)NSMutableArray * tacticArray;
@property (retain ,nonatomic)UITableView * tableView;
@property (retain ,nonatomic)UICollectionView * collectionView;
@property (retain ,nonatomic)UIView * redView;
@property (retain ,nonatomic)UIView * view1;
@property (retain ,nonatomic)UIView * view2;
@property (assign ,nonatomic)int presentOffset;
@property (assign ,nonatomic)int TacticOffset;
@property (retain ,nonatomic)StyleLabel * label1;
@property (retain ,nonatomic)StyleLabel * label2;

@end

@implementation SearchDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:245 / 255.0 blue:245 / 255.0 alpha:1];
    _presentOffset = 0;
    _TacticOffset = 0;
    [self createScrollView];
    [self getPresentData];
    [self getTacticData];
}

- (void)createScrollView {
    NSArray * arr = @[@"礼物",@"攻略"];
    for (int i = 0; i < 2; i ++) {
        UIButton * btn = [UIButton buttonWithType: UIButtonTypeSystem];
        btn.frame = CGRectMake(i * theScreenWidth / 2, 0 , theScreenWidth / 2, 40);
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        btn.tag = 10 + i;
        [self.view addSubview:btn];
    }
    _redView = [[UIView alloc] initWithFrame:CGRectMake(0, 38, theScreenWidth / 2, 2)];
    _redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_redView];
    
    _mainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 40, theScreenWidth, theScreenHeight - 64 - 40)];
    _mainScroll.contentSize = CGSizeMake(theScreenWidth * 2, theScreenHeight - 64 - 40);
    _mainScroll.delegate = self;
    _mainScroll.showsHorizontalScrollIndicator = NO;
    _mainScroll.bounces = NO;
    _mainScroll.pagingEnabled = YES;
    [self.view addSubview:_mainScroll];
    _view1 = [[UIView alloc] init];
    _view2 = [[UIView alloc] init];
    _view1.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
    _view2.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
    
//    **************tableView********************
    _tableView  = [[UITableView alloc] initWithFrame:CGRectMake(theScreenWidth, 0, theScreenWidth, theScreenHeight - 64 - 40) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 130;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView addHeaderWithTarget:self action:@selector(TheaderAction)];
    [_tableView addFooterWithTarget:self action:@selector(TfooterAction)];
    _tableView.headerRefreshingText = @"正在刷新哟";
    _tableView.footerRefreshingText = @"正在加载哟";
    [_tableView registerNib:[UINib nibWithNibName:@"GuideContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"tableViewCell"];
    [_mainScroll addSubview:_tableView];
    
    
    
//    **************collectionView********************
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenHeight - 64 - 40) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:245 / 255.0 blue:245 / 255.0 alpha:1];
    [_collectionView addHeaderWithTarget:self action:@selector(CheaderAction)];
    [_collectionView addFooterWithTarget:self action:@selector(CfooterAction)];
    _collectionView.headerRefreshingText = @"正在刷新哟";
    _collectionView.footerRefreshingText = @"正在加载哟";
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
    [_mainScroll addSubview:_collectionView];
    [_mainScroll addSubview:_view1];
    [_mainScroll addSubview:_view2];
    _label1 = [[StyleLabel alloc] initWithFrame:CGRectMake(0, theScreenHeight / 2 - 80, theScreenWidth, 20)];
    _label2 = [[StyleLabel alloc] initWithFrame:CGRectMake(0, theScreenHeight / 2 - 80, theScreenWidth, 20)];
    [_view1 addSubview:_label1];
    [_view2 addSubview:_label2];
}

- (void)TheaderAction{
    _TacticOffset = 0;
    [self getTacticData];
}

- (void)TfooterAction{
    _TacticOffset += 20;
    [self getTacticData];
}

- (void)CheaderAction{
    _presentOffset = 0;
    [self getPresentData];
}

- (void)CfooterAction{
    _presentOffset += 20;
    [self getPresentData];
}


- (void)btnAction:(UIButton *)btn{
    [_mainScroll setContentOffset:CGPointMake((btn.tag - 10) * theScreenWidth, 0) animated:YES];
    _redView.frame = CGRectMake((btn.tag - 10) * theScreenWidth / 2, 38, theScreenWidth / 2, 2);
}

- (void)getPresentData{
    
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    [manager getSearchPresentDataWithUrl:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?sort=&limit=20&offset=%d&keyword=%@",_presentOffset,_searchKey] andBlock:^(id respond) {

        if (_presentOffset == 0) {
            _presentArray = [[NSMutableArray alloc] initWithArray:respond];
            [_collectionView headerEndRefreshing];
        }else{
            [_presentArray addObjectsFromArray:respond];
            [_collectionView footerEndRefreshing];
        }
        if (_presentArray.count == 0) {
            _view1.frame = CGRectMake(0, 0, theScreenWidth, theScreenHeight - 104);
            _label1.alpha = 1;
        }else{
            _view1.frame = CGRectMake(0, 0, 0, 0);
            _label1.alpha = 0;
            [_collectionView reloadData];
        }
    }];
    
}//http://api.liwushuo.com/v2/search/item?sort=&limit=20&offset=0&keyword=毕业礼物
//http://www.liwushuo.com/items/1014109 UIWebView

- (void)getTacticData{
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    [manager getSearchTacticDataWithUrl:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/post?sort=&limit=20&offset=%d&keyword=%@",_TacticOffset,_searchKey] andBlock:^(id respond) {
        
        if (_TacticOffset == 0) {
            _tacticArray = [[NSMutableArray alloc] initWithArray:respond];
            [_tableView headerEndRefreshing];
        }else{
            [_tacticArray addObjectsFromArray:respond];
            [_tableView footerEndRefreshing];
        }
        if (_tacticArray.count == 0) {
            _view2.frame = CGRectMake(theScreenWidth, 0, theScreenWidth, theScreenHeight - 104);
            _label2.alpha = 1;
        }else{
            _view2.frame = CGRectMake(0, 0, 0, 0);
            _label2.alpha = 0;
            [_tableView reloadData];
        }
    }];
    
}

#pragma mark tableview协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tacticArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SearchItem * item = _tacticArray[indexPath.row];
    static NSString * cellId = @"tableViewCell";
    GuideContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    [cell.backGroundImage setImageWithURL:[NSURL URLWithString:item.cover_image_url]];
    CALayer * layer = cell.backGroundImage.layer;
    layer.cornerRadius = 5;
    layer.masksToBounds = YES;
    cell.title.text = item.title;
    cell.favouriteLabel.text = [NSString stringWithFormat:@"%d",[item.likes_count intValue]];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

        SearchItem * item = _tacticArray[indexPath.row];
        DetailViewController * vc = [[DetailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:NO];
        vc.Id = item.Id;
}





#pragma mark collectionview协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _presentArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SearchItem * item = _presentArray[indexPath.row];
    static NSString * cellid = @"collectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
    [cell.layer setCornerRadius:5];
    [cell.layer setMasksToBounds:YES];
    
    cell.backgroundColor = [UIColor whiteColor];
    UIImageView * imageView = (UIImageView *)[cell.contentView viewWithTag:101];
    if (imageView == nil) {
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (theScreenWidth - 30) / 2, (theScreenWidth - 30) / 2)];
        [cell.contentView addSubview:imageView];
        imageView.tag = 101;
    }
    UILabel * nameLabel = (UILabel *)[cell.contentView viewWithTag:102];
    if (nameLabel == nil) {
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, (theScreenWidth - 30) / 2 + 5, (theScreenWidth - 30) / 2 - 10, 40)];
        nameLabel.numberOfLines = 2;
        nameLabel.tag = 102;
        nameLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:nameLabel];
    }
    UILabel * priceLabel = (UILabel *)[cell.contentView viewWithTag:103];
    if (priceLabel == nil) {
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, (theScreenWidth - 30) * 3 / 4 - 30, 75, 20)];
        priceLabel.tag = 103;
        priceLabel.textColor = [UIColor redColor];
        priceLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:priceLabel];
    }
    UILabel * favouriteLabel = (UILabel *)[cell.contentView viewWithTag:104];
    if (favouriteLabel == nil) {
        favouriteLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, (theScreenWidth - 30) * 3 / 4 - 30, 40, 20)];
        favouriteLabel.numberOfLines = 2;
        favouriteLabel.tag = 104;
        favouriteLabel.textColor = [UIColor grayColor];
        favouriteLabel.font = [UIFont systemFontOfSize:12];
        [cell.contentView addSubview:favouriteLabel];
    }
    
    [imageView setImageWithURL:[NSURL URLWithString:item.cover_image_url]];
    nameLabel.text = item.name;
    priceLabel.text = item.price;
    float price = [item.favorites_count intValue] / 1000.0;
    favouriteLabel.text = [NSString stringWithFormat:@"%0.1fk",price];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((theScreenWidth - 30) / 2, (theScreenWidth - 30) * 3 / 4);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HotDetailViewController * vc = [[HotDetailViewController alloc] init];
    SearchItem * item = _presentArray[indexPath.row];
    vc.webStr = [NSString stringWithFormat:@"http://www.liwushuo.com/items/%@",item.Id];
    [self.navigationController pushViewController:vc animated:YES];
    
}

//返回列与列之间最小的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}

#pragma mark scrollView 协议方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    _redView.frame = CGRectMake(scrollView.contentOffset.x / 2, 38 + 64, theScreenWidth / 2, 2);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
